#coding=utf-8
from . import blog
import os,re
from werkzeug.utils import secure_filename
from datetime import datetime
from flask import render_template, flash, request, url_for, redirect, current_app, g, abort,send_from_directory,request,jsonify
from flask_babel import gettext as _
from flask_login import login_user, logout_user, login_required, current_user
from ..utils import get_categories
from .. import lm, db
from app.models import User, Post, Comment, Tag, Permission
from .forms import LoginForm, SignupForm, ProfileForm, PostForm, CommentForm
from ..decorators import admin_required
import re

@blog.route('/')
@blog.route('/index')
def index():
    user = current_user
    categories = ([], [])
    if g.user.is_authenticated:
        user = User.query.get_or_404(g.user.id)
        categories = get_categories(user)
    page = request.args.get('page', 1, type=int)
    pagination = Post.query.order_by(Post.created_date.desc()).paginate(page, per_page=5, error_out=False)
    posts = pagination.items
    return render_template('index.html', **locals())

@blog.route('/ueditor/config')
def ueditor_config():
    return send_from_directory(os.path.join(current_app.root_path, 'static'),
                               'ueditor/config.json', mimetype='text/html')

@blog.route('/ueditor/uploadimage',methods=['POST'])
def ueditor_uploadimage():
    current_app.config['UPLOAD_FOLDER']=os.path.join(current_app.root_path,'static/upload/image')
    file = request.files['upfile']
    filename=secure_filename(file.filename)
    file.save(os.path.join(current_app.config['UPLOAD_FOLDER'],filename))
    return jsonify(state='SUCCESS',
                   url="/static/upload/image/"+filename,
                   title=filename)


@blog.route('/user/<username>')
def user(username):
    user = User.query.get_by_username(username)
    categories = get_categories(user)
    page = request.args.get('page', 1, type=int)
    # posts = g.user.followed_posts().all()
    pagination = Post.query.filter_by(author_id=user.id).order_by(Post.created_date.desc()).paginate(page, per_page=5, error_out=False)
    posts = pagination.items
    # return render_template('user_home.html', user=user, posts=posts, pagination=blogs, categorys=categorys)
    return render_template('user_home.html', **locals())

@blog.route('/userhome')
def userhome():
    if g.user.is_anonymous:
        return index()
    #they are equal,current_user is login send to obj, see flask_login
    page = request.args.get('page', 1, type=int)
    categories = get_categories(g.user)
    # posts = g.user.followed_posts().all()
    blogs = Post.query.filter_by(author_id=g.user.id).order_by(Post.created_date.desc()).paginate(page, per_page=5, error_out=False)
    posts = blogs.items
    return render_template('user_home.html', posts=posts, categories = categories, user=g.user, pagination=blogs)



@blog.route('/login', methods=['GET', 'POST'])
def login():
    login_form = LoginForm()
    if login_form.validate_on_submit():
        user, authenticated = User.query.authenticate(login_form.username.data,
                                                      login_form.password.data)
        if user and authenticated:
            remeber_me = login_form.remember.data
            login_user(user, remember=remeber_me)
            flash("Welcome back")
            next_url = login_form.next.data

            if not next_url or next_url == request.path:
                next_url = url_for('.user', username=user.username)

            return redirect(next_url)
        else:
            flash(_("Sorry, invalid login"), "error")

    return render_template('login.html', form=login_form)


@blog.route('/logout')
def logout():
    logout_user()
    flash('You have been logged out.')
    return redirect(url_for('.index'))


@blog.route('/signup', methods=['GET', 'POST'])
def signup():
    signup_form = SignupForm()
    if signup_form.validate_on_submit():
        user = User()
        signup_form.populate_obj(user)
        if not User.check_username(user.username):
            flash("Username has been used by others!")
            return redirect('.signup')
        if not User.check_email(user.email):
            flash("Email has been used by others!")
            return redirect('.signup')
        user.set_role()

        db.session.add(user)
        db.session.commit()
        flash("Welcome for register")
        next_url = signup_form.next.data

        if not next_url or next_url == request.path:
            next_url = url_for('.login')

        return redirect(next_url)

    return render_template('signup.html', form=signup_form)


@blog.route('/search')
def search():
    user = current_user
    categories = ([], [])
    if g.user.is_authenticated:
        user = User.query.get_or_404(g.user.id)
        categories = get_categories(user)
    page = request.args.get('page', 1, type=int)
    keywords = request.args.get('q','').strip()
    # blogs = Post.query.get_posts_by_tag(page=page, tag=keywords)
    if keywords[0:4] == 'tag:':
        keywords = keywords[4:]
        tags = Post.query.filter(Post.tags.any(name=keywords)).order_by(Post.created_date.desc()).paginate(page, current_app.config['SEARCH_POSTS_PER_PAGE'], False)
        posts = tags.items
    elif keywords[0:6] == 'title:':
        keywords = keywords[6:]
        titles = Post.query.filter(Post.title.like('%'+keywords+'%')).order_by(Post.created_date.desc()).paginate(page, current_app.config['SEARCH_POSTS_PER_PAGE'], False)
        posts = titles.items
    else:
        tags = Post.query.filter(Post.tags.any(name=keywords)).order_by(Post.created_date.desc()).paginate(page, current_app.config['SEARCH_POSTS_PER_PAGE'], False)
        titles = Post.query.filter(Post.title.like('%'+keywords+'%')).order_by(Post.created_date.desc()).paginate(page, current_app.config['SEARCH_POSTS_PER_PAGE'], False)
        posts = titles.items+tags.items
    return render_template('index.html', **locals())


# @blog.route('/admin')
# @login_required
# @admin_required
# def admin():
#     return 'Just for admin'


@blog.route('/profile/<username>')
def profile(username):
    user = User.query.get_by_username(username)
    return render_template('profile.html', user=user)


@blog.route('/edit_profile', methods=['GET', 'POST'])
def edit_profile():
    profile_form = ProfileForm()
    user = current_user
    if profile_form.validate_on_submit():
        profile_form.populate_obj(user)
        db.session.add(user)
        db.session.commit()

        return render_template('profile.html', user=user)

    return render_template('edit_profile.html', form=profile_form)


@blog.route('/category/<int:user_id>/<category_name>')
def category(user_id, category_name):
    user = User.query.get_or_404(user_id)
    categories = get_categories(user)
    blogs = Post.query.filter(Post.author_id ==user_id, Post.tags.any(name=category_name)).order_by(Post.created_date.desc()).paginate(1, current_app.config['SEARCH_POSTS_PER_PAGE'], False)
    posts = blogs.items
    return render_template('user_home.html', **locals())


@blog.route('/post/<int:id>', methods=['GET', 'POST'])
def post(id):
    post = Post.query.get_or_404(id)
    comment_form = CommentForm()
    if comment_form.validate_on_submit():
        comment = Comment(comment=comment_form.body.data,
                          post=post,
                          author=current_user._get_current_object())
        db.session.add(comment)
        db.session.commit()
        flash('Your comment has been published.')
        return redirect(url_for('.post', id=post.id, page=-1))
    page = request.args.get('page', 1, type=int)
    if page == -1:
        page = (post.comments.count() - 1) // \
            current_app.config['FLASKY_COMMENTS_PER_PAGE'] + 1
    pagination = post.comments.order_by(Comment.created_date.asc()).paginate(
        page, per_page=current_app.config['FLASKY_COMMENTS_PER_PAGE'],
        error_out=False)
    comments = pagination.items

    user = current_user
    categories = ([], [])
    if g.user.is_authenticated:
        user = User.query.get_or_404(g.user.id)
        categories = get_categories(user)
    return render_template('post.html',form=comment_form, **locals())


@blog.route('/editpost/<int:id>', methods=['GET', 'POST'])
@login_required
def post_form(id):
    post_form = PostForm()
    if not post_form.validate_on_submit():
        edit_post = Post.query.get(id)
        if edit_post is not None:
            if current_user != edit_post.author and \
                not current_user.can(Permission.ADMINISTER):
                abort(403)
            post_form.title.data = edit_post.title
            post_form.content.data = edit_post.content
            post_form.tags.data = ''
            for tag in edit_post.tags:
                post_form.tags.data += tag.name
                post_form.tags.data += ','
            if len(post_form.tags.data) > 0:
                post_form.tags.data = post_form.tags.data[:-1]
            # db.session.delete(edit_post)
            # db.session.commit()
    else:
        is_edit = False
        post = None
        if id:
            post = Post.query.get(id)
        if post is not None:
            is_edit = True
            post.title = post_form.title.data
            post.content = post_form.content.data
        else:
            post = Post(title=post_form.title.data, content=post_form.content.data)
        post.main_content = re.sub(r'<[^>]+>','',post.content).strip()[:100]
        post.author = current_user
        for tag in post_form.tags.data.split(','):
            my_tag = Tag.query.filter_by(name=tag).first()
            if my_tag is None:
                my_tag = Tag(name=tag)
            post.tags.append(my_tag)
        if not is_edit:
            db.session.add(post)
        db.session.commit()

        return redirect(url_for('.post', id=post.id))

    return render_template('edit_post.html', form=post_form)


@blog.route('/delete_post/<int:id>')
def delete_post(id):
    post = Post.query.get(id)
    if post is not None:
        db.session.delete(post)
        db.session.commit()

    return redirect(url_for('.user', username=g.user.username))


@lm.user_loader
def load_user(user_id):
    return User.query.get(int(user_id))


@blog.before_request
def before_request():
    g.user = current_user
    if g.user.is_authenticated:
        g.user.last_login = datetime.utcnow()
        db.session.add(g.user)
        db.session.commit()

